package xyz.kongbai121.common.utils;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.baomidou.mybatisplus.core.toolkit.StringPool;

import java.util.concurrent.ThreadLocalRandom;

/**
 * @author ljq
 * @version 1.0.0
 * @Description
 * <p>
 * 高效GUID产生算法(sequence),基于Snowflake实现64位自增ID算法。 <br>
 * 优化开源项目 http://git.oschina.net/yu120/sequence
 * </p>
 * @createTime 2021年11月11日
 */
public class IdWorker {

    /**
     * 主机和进程的机器码
     */
    private static Sequence WORKER = new Sequence();

    /**
     * 有参构造器
     * @param workerId     工作机器 ID
     * @param datacenterId 序列号
     */
    public static void initSequence(long workerId, long datacenterId) {
        WORKER = new Sequence(workerId, datacenterId);
    }

    /**
     * 获取ID
     */
    public static long getId() {
        return WORKER.nextId();
    }

    /**
     * 获取ID
     */
    public static String getIdStr() {
        return String.valueOf(WORKER.nextId());
    }

    /**
     * 得到16位的UUID-(数字)
     */
    public static String getUUID_16() {
        int machineId = 1;// 最大支持1-9个集群机器部署

        int hashCodeV = UUID.randomUUID().toString().hashCode();
        if (hashCodeV < 0) {// 有可能是负数
            hashCodeV = -hashCodeV;
        }
        String string = machineId + String.format("%015d", hashCodeV);
        return string;
    }

    /**
     * 得到32位的UUID-(数字) 去掉"-"
     */
    public static String getUUID_32() {
        return UUID.randomUUID().toString().replace(StringPool.DASH, StringPool.EMPTY).toLowerCase();
    }

    /**
     * 使用ThreadLocalRandom获取UUID获取更优的效果 去掉"-"
     */
    public static String getUUID32() {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        return new java.util.UUID(random.nextLong(), random.nextLong()).toString().replace(StringPool.DASH, StringPool.EMPTY);
    }

    /**
     * 得到8位的UUID-(码)
     */
    public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
            "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8",
            "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
            "U", "V", "W", "X", "Y", "Z" };
    public static String getUUID_8() {
        StringBuffer shortBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars[x % 0x3E]);
        }
        return shortBuffer.toString();
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            System.out.print("生成ID：" + getId() + " ");
            System.out.println("生成ID：" + getUUID_8());
        }
    }
}
